<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 前台商品ajax类
 * @package  ajax
 * @subpackage  shop
 * @author   allen.qiang
 */

quanli_require('module/base/shop/shopCart.class.php');
//加载活动配置类 add by allen.qiang 2015-05-15
quanli_require('module/base/activity/activityConfig.class.php');
class ajax_cart {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && quanli_is_int($_REQUEST['operFlg'])) {

            switch($_REQUEST['operFlg']) {

                case 1: //获得购物车列表
                    $this->getCartList();
                    break;

                case 2: //添加普通商品到购物车
                    $this->addGeneralGoods();
                    break;

                case 3: //更新普通商品购物车商品数量
                    $this->updateGeneralGoods();
                    break;

                case 4: //删除购物车商品
                    $this->deleteGoods();
                    break;

                case 5: //清空购物车
                    $this->emptyCart();
                    break;

                case 6: //加载购物车商品信息
                    $this->loadCart();
                    break;

                case 7: //更新商品切分
                    $this->segmentation();
                    break;

                case 8: //更新普通商品购物车商品磅数
                    $this->updateGoodsSpec();
                    break;

                case 10: //立即购买
                    $this->nowBuy();
                    break;

                case 11: //设置暂时购买
                    $this->isBuy();
                    break;

                case 12: //更新购物车已选够商品
                    $this->updateCartGoods();
                    break;

                case 13: //添加多个商品到购物车
                    $this->addGoodsToCart();
                    break;

                default:
                    returnJsonData('参数错误');
                    break;

            }

        } else {

            returnJsonData('参数错误');

        }

    }

    /**
     * 加载购物车数据
     */
    private function loadCart(){

        global $G_SHOP;

        //实例购物车类
        $shopCart = new shopCart();

        $shop_array = $shopCart->loadCart();

        $sql = 'SELECT postID, twoPostID, spec FROM goods_sale WHERE useFlg = 1 ';
        $spec_array = $G_SHOP->DBCA->stmt_query($sql);

        $result_array = array();
        if($spec_array){
            foreach($spec_array as $spec){
                $result_array[$spec->twoPostID][$spec->postID] = $spec->spec;
            }

            foreach($shop_array['goods'] as $key => $goods){
                $shop_array['goods'][$key]['specArr'] = $result_array[$goods['twoPostID']];
            }

        }

        returnJsonData('ok', 200, $shop_array);

    }

    /**
     * 立即购买
     */
    private function nowBuy() {

        if (!isset($_REQUEST['postID'], $_REQUEST['goods_amount']) || !quanli_is_int($_REQUEST['postID'])) {
            returnJsonData('参数错误');
        }

        if (!quanli_is_int($_REQUEST['goods_amount'])) {
            $_REQUEST['goods_amount'] = 1;
        }

        //实例购物车类
        $shopCart = new shopCart();

        //添加普通商品到购物车
        $result_array = $shopCart->nowBuy($_REQUEST['postID'], $_REQUEST['goods_amount']);

        if ($result_array['code'] == 200) {
            returnJsonData($result_array['message'], $result_array['code'], $result_array['data']);
        } else {
            returnJsonData($result_array['message'], $result_array['code']);
        }

    }

    /**
     * 获得购物车列表
     */
    private function getCartList() {



    }

    /**
     * 添加普通商品到购物车
     */
    public function addGeneralGoods() {

        global $G_SHOP;

        if (!isset($_REQUEST['postID'], $_REQUEST['goods_amount']) || !quanli_is_int($_REQUEST['postID'])) {
            returnJsonData('参数错误');
        }

        if (!quanli_is_int($_REQUEST['goods_amount'])) {
            $_REQUEST['goods_amount'] = 1;
        }

        //实例购物车类
        $shopCart = new shopCart();

        $cart_array = $shopCart->getCartInfo();

        //加载系统全局设置信息 add by allen.qiang 2015-05-15 Start

        //实例化系统配置类
        $systemConfig = new activityConfig('systemConfig');
        $config = $systemConfig->config;

        //限购数量
        if(isset($config['goods_limit_num']) && !empty($config['goods_limit_num'])){

            $goods_limit = (array)json_decode($config['goods_limit_num']);
            $goods_limit_txt = (array)json_decode($config['goods_limit_txt']);

            $goodsLimit = $goodsLimitTxt = array();

            foreach($goods_limit as $procut_code => $num){

                $result = $G_SHOP->DBCA->stmt_query("SELECT postID FROM goods_sale WHERE product_code = '{$procut_code}'");

                foreach($result as $row){

                    $goodsLimit[$row->postID] = $num;

                    if(isset($goods_limit_txt[$procut_code])){
                        $goodsLimitTxt[$row->postID] = $goods_limit_txt[$procut_code];
                    }
                }
            }

            //判断限购数量
            $postID = $_REQUEST['postID'];
            $goods_amount = $cart_array['goods']['general'][$postID]['goods_amount'];
            $goods_amount += intval($_REQUEST['goods_amount']);

            if(isset($goodsLimit[$postID]) && $goods_amount>$goodsLimit[$postID]){
                $msg = isset($goodsLimitTxt[$postID])?$goodsLimitTxt[$postID]:'所选商品购买数量上限个数为'. $goodsLimit[$postID] .',请重新选择此商品或再次选择其它商品';
                returnJsonData($msg);
            }

        }

        //加载系统全局设置信息 add by allen.qiang 2015-05-15 End

        /**
         * ======================================
         * 判断商品数量是否超过上限->上限数量50
         * ======================================
         */

        if(isset($cart_array['goods']['general'][$_REQUEST['postID']])){

            $goods_amount = $cart_array['goods']['general'][$_REQUEST['postID']]['goods_amount'];
            if($goods_amount + $_REQUEST['goods_amount'] > 50){
                $out_amount = $goods_amount + $_REQUEST['goods_amount'] -50;
                returnJsonData('所选商品购买数量上限50,现已超出上限个数为'. $out_amount .',请重新选择此商品或再次选择其它商品');
            }
        }

        /**
         * ======================================
         * 判断商品数量是否超过上限->上限数量50
         * ======================================
         */


        //添加普通商品到购物车
        $result_array = $shopCart->addGeneralGoods($_REQUEST['postID'], $_REQUEST['goods_amount']);

        if ($result_array['code'] == 200) {
            returnJsonData($result_array['message'], $result_array['code'], $result_array['data']);
        } else {
            returnJsonData($result_array['message'], $result_array['code']);
        }

    }

    /**
     * 更新普通商品购物车商品数量
     */
    private function updateGeneralGoods() {

        if (!isset($_REQUEST['index'], $_REQUEST['goods_amount']) || !quanli_is_int($_REQUEST['index'], 2) || !quanli_is_int($_REQUEST['goods_amount'])) {
            returnJsonData('参数错误');
        }

        //实例购物车类
        $shopCart = new shopCart();

        //删除购物车商品
        $result_array = $shopCart->updateGeneralGoods($_REQUEST['index'], $_REQUEST['goods_amount']);

        if ($result_array['code'] == 200) {

            $shop_array = $shopCart->loadCart();

            $return_array = array(
                'goods' => $result_array['data'],
                'goods_list' => $shop_array
            );
            returnJsonData($result_array['message'], $result_array['code'], $return_array);

        } else {

            returnJsonData($result_array['message'], $result_array['code']);

        }

    }


    /**
     * 删除购物车商品
     */
    public function deleteGoods () {

        if (!isset($_REQUEST['index']) || !quanli_is_int($_REQUEST['index'], 2)) {
            returnJsonData('参数错误');
        }

        //实例购物车类
        $shopCart = new shopCart();

        //删除购物车商品
        $result_array = $shopCart->delete($_REQUEST['index']);

        if ($result_array['code'] == 200) {

            $shop_array = $shopCart->loadCart();
            $return_array = array(
                'goods' => $result_array['data'],
                'goods_list' => $shop_array
            );
            returnJsonData($result_array['message'], $result_array['code'], $return_array);

        } else {

            returnJsonData($result_array['message'], $result_array['code']);

        }

    }


    /**
     * 清空购物车
     */
    public function emptyCart () {

        //实例购物车类
        $shopCart = new shopCart();

        $result_array = $shopCart->emptyCart();

        returnJsonData($result_array['message'], $result_array['code']);

    }

    /**
     * 更新商品切分
     */
    private function segmentation() {

        if (!isset($_REQUEST['sync_id'], $_REQUEST['index']) || !quanli_is_int($_REQUEST['sync_id'], 2) || !quanli_is_int($_REQUEST['index'], 2)) {
            returnJsonData('参数错误');
        }

        //实例购物车类
        $shopCart = new shopCart();

        //更新商品切分
        $result_array = $shopCart->segmentation($_REQUEST['sync_id'], $_REQUEST['index']);

        returnJsonData($result_array['message'], $result_array['code']);

    }

    /**
     * 设置暂时购买状态
     * 状态：0=>不购买  1=>暂时购买
     */

    private function isBuy(){
        var_dump($_REQUEST);
        if(!isset($_REQUEST['id']) || !is_numeric($_REQUEST['id'])){
            returnJsonData('参数错误');
        }

        if(!isset($_REQUEST['sign']) || !is_numeric($_REQUEST['sign'])){
            returnJsonData('参数错误');
        }

        //参数：0 => 全取消/全选
        $id = $_REQUEST['id'];
        $sign = $_REQUEST['sign'];

        //实例购物车类
        $shopCart = new shopCart();

        $bill_array = $shopCart->getCartInfo();
        $cart_array = &$bill_array['goods'];

        if (isset($cart_array['general'])) {

            if($id == 0){
                foreach ($cart_array['general'] as &$list) {
                    $list['is_buy'] = $sign;
                }
            }

            if($id > 0){

                if(!isset($cart_array['general'][$id]))
                    returnJsonData('该商品不存在，请刷新重试!');

                $cart_array['general'][$id]['is_buy'] = $sign;
            }
        }

        $shopCart->setCartInfo($bill_array);

        returnJsonData('ok', 200);

    }

    /**
     * 更新购物车已选购商品
     * @author create by allen.qiang
     */
    private function updateCartGoods(){

        //实例购物车类
        $shopCart = new shopCart();

        //更新购物车商品
        $result = $shopCart->updateCartGoods();

        if($result['code'] != 200)
            return null;

        returnJsonData( 'ok', 200, $result['data'] );

    }

    /**
     * 修改购物车已选商品的磅数
     * @author create by allen.qiang
     */

    private function updateGoodsSpec(){

        global $G_SHOP;

        if (!isset($_REQUEST['index'], $_REQUEST['goods_spec'], $_REQUEST['goods_amount']) || !quanli_is_int($_REQUEST['index'], 2) || empty($_REQUEST['goods_spec']) || !quanli_is_int($_REQUEST['goods_amount'])) {
            returnJsonData('参数错误');
        }

        $sql = 'SELECT twoPostID FROM goods_sale WHERE postID = ' . $_REQUEST['index'];
        $twoPostID_array = $G_SHOP->DBCA->stmt_query($sql);

        $sql = 'SELECT * FROM goods_sale WHERE twoPostID = ' . $twoPostID_array[0]->twoPostID . ' AND spec = '. '\''.$_REQUEST['goods_spec'].'\'';
        $good_array = $G_SHOP->DBCA->stmt_query($sql);

        if(!$good_array){
            returnJsonData('请选择正确的商品磅数');
        }else if($good_array[0]->useFlg == 0){
            returnJsonData('此商品该磅数已停产,请选择其他磅数');
        }

        //实例购物车类
        $shopCart = new shopCart();

        //删除购物车商品
        $result_array = $shopCart->updateGoodsSpec($_REQUEST['index'], $good_array[0]->postID, $_REQUEST['goods_amount']);

        if ($result_array['code'] == 200) {

            $shop_array = $shopCart->loadCart();

            $return_array = array(
                'goods' => $result_array['data'],
                'goods_list' => $shop_array
            );

            returnJsonData($result_array['message'], $result_array['code'], $return_array);

        } else {

            returnJsonData($result_array['message'], $result_array['code']);

        }


    }

    //添加多个商品到购物车（不管是否下架或售罄都可以加购物车，用于活动专题）
    private function addGoodsToCart(){

        global $G_SHOP;

        $ids = $_REQUEST['ids'];//商品id数组
        $nums = $_REQUEST['nums'];//商品数量数组
        $act = isset($_REQUEST['act'])&&!empty($_REQUEST['act'])?trim($_REQUEST['act']):'shop_cart';//设置购物车名称

        //加载类文件
        quanli_include('module/base/goods/quanliGoods.class.php');
        quanli_include('module/base/goods/goodsFittings.class.php');
        quanli_require('module/base/activity/activityConfig.class.php');

        //实例商品配件类
        $goodsFittings = new goodsFittings( $G_SHOP->DBCA );

        //实例商品类
        $quanliGoods = new quanliGoods( $G_SHOP->DBCA );

        //实例活动配置类
        $activityConfig = new activityConfig($act);

        $config = $activityConfig->config;

        //活动是否有效
        $haveActivity = false;

        //如果活动在线
        if($config && date('Y-m-d H:i:s')>$config['start_time'] && date('Y-m-d H:i:s')<$config['end_time']){

            $haveActivity = true;

            //判断今天是否在已排除的周期活动内
            if(isset($config['exclude_week']) && !empty($config['exclude_week'])){

                $w = date('w');
                if(is_array(json_decode($config['exclude_week'])) && in_array($w,json_decode($config['exclude_week']))){
                    $haveActivity = false;
                    returnJsonData( '今天不能订购',404);
                }
            }

            //限购数量
            if($haveActivity && isset($config['goods_limit_num']) && !empty($config['goods_limit_num'])){

                $goods_limit = (array)json_decode($config['goods_limit_num']);
                $goods_limit_txt = (array)json_decode($config['goods_limit_txt']);

                $goodsLimit = $goodsLimitTxt = array();

                foreach($goods_limit as $procut_code => $num){

                    $result = $G_SHOP->DBCA->stmt_query("SELECT postID FROM goods_sale WHERE product_code = '{$procut_code}'");

                    foreach($result as $row){

                        $goodsLimit[$row->postID] = $num;

                        if(isset($goods_limit_txt[$procut_code])){
                            $goodsLimitTxt[$row->postID] = $goods_limit_txt[$procut_code];
                        }
                    }
                }
            }
        }

        $city_id = $G_SHOP->get_cookie_info('EBSIG_CITY_ID');

        //实例购物车类
        $shopCart = new shopCart();

        //购物车信息
        $bill_array = $shopCart->getCartInfo($act);
        $cart_array = & $bill_array['goods'];
        $cart_array['general'] = array();

        //循环添加到自定义购物车
        foreach($ids as $key => $id){

            $postID = intval($id);
            $goods_amount = intval($nums[$key]);

            //查询商品信息
            $arg_array = array(
                'postID' => $postID
            );

            $goods_array = $quanliGoods->searchGoodsSaleDetail( $arg_array );
            if (!$goods_array) {
                returnJsonData( '商品信息没有找到',404);
            }
            if ($goods_array['cityID'] != $city_id) {
                returnJsonData( '此款产品在当前地区暂不支持配送',404);
            }
//            if ($goods_array['useFlg'] == 0 || $goods_array['useFlg'] == 2 || $goods_array['useFlg'] == 3) {
//                returnJsonData( '商品已下架或售罄',404);
//            }

            //判断限购数量
            if(isset($goodsLimit[$postID]) && $goods_amount>$goodsLimit[$postID]){
                $msg = isset($goodsLimitTxt[$postID])?$goodsLimitTxt[$postID]:'选购数量不能超过'.$goodsLimit[$postID];
                returnJsonData($msg,404);
            }

            //判断是否限购数量

            //查询商品配件
            $arg_array = array(
                'postID' => $postID
            );
            $goods_fittings_array = $goodsFittings->searchGoodsFitsRelation( $arg_array );

            //购物车商品数组结构
            $goods_array['goods_amount'] = $goods_amount;
            $goods_array['fittings'] = $goods_fittings_array;
            $cart_goods_array = $shopCart->createCartGoodsStructure( $goods_array);
            $cart_array['general'][$postID] = $cart_goods_array;
        }

        //保存购物车信息
        $shopCart->setCartInfo($bill_array,$act);

        if(count($cart_array['general']) == count($ids)){
            returnJsonData('ok',200);
        }else{
            returnJsonData('提交失败',404);
        }
        unset($G_SHOP);
    }
}